package com.xjnt.frameworks.plugin.sql.criterion.expression;

import com.xjnt.frameworks.plugin.sql.criterion.Criterion;
import com.xjnt.frameworks.plugin.sql.criterion.SqlCriteria;
import com.xjnt.frameworks.plugin.sql.criterion.TypedValue;

public class LogicalExpression implements Criterion {

	private static final long serialVersionUID = 1L;
	
	private final Criterion lhs;
	private final Criterion rhs;
	private final String op;

	public LogicalExpression(Criterion lhs, Criterion rhs, String op) {
		this.lhs = lhs;
		this.rhs = rhs;
		this.op = op;
	}

	@Override
	public String toSql(SqlCriteria criterion) {
		StringBuilder sql = new StringBuilder();
		sql.append("(");
		sql.append(lhs.toSql(criterion));
		sql.append(" ");
		sql.append(getOp());
		sql.append(" ");
		sql.append(rhs.toSql(criterion));
		sql.append(")");
		return sql.toString();
	}

	@Override
	public TypedValue[] getTypedValues(SqlCriteria criterion) {
		final TypedValue[] lhsTypedValues = lhs.getTypedValues( criterion );
		final TypedValue[] rhsTypedValues = rhs.getTypedValues( criterion );

		final TypedValue[] result = new TypedValue[ lhsTypedValues.length + rhsTypedValues.length ];
		System.arraycopy( lhsTypedValues, 0, result, 0, lhsTypedValues.length );
		System.arraycopy( rhsTypedValues, 0, result, lhsTypedValues.length, rhsTypedValues.length );
		return result;
	}

	public String getOp() {
		return op;
	}
}
